<template>
  <ElDialog v-model="dialogVisible" :title="title" :width="width" align-center>
    <ElForm ref="refElForm" :model="formField" :label-width="labelWidth" :rules="formData.rules">
      <ElRow>
        <template v-for="(item, index) in formData.columns" :key="index">
          <ElCol :span="item.span ?? 24" v-if="!item.hidden">
            <ElFormItem :label="item.title" :prop="item.name">
              <!-- 文本输入框 -->
              <ElInput
                v-if="item.type == CustomFormColumnsType.input"
                v-model="formField[item.name]"
                :placeholder="'请输入' + item.title"
                :disabled="item.disabled"
                clearable
              ></ElInput>
              <!-- 密码输入框 -->
              <ElInput
                v-if="item.type == CustomFormColumnsType.password"
                v-model="formField[item.name]"
                type="password"
                :placeholder="'请输入' + item.title"
                :disabled="item.disabled"
                clearable
              ></ElInput>
              <!-- 多行文本 -->
              <ElInput
                v-if="item.type == CustomFormColumnsType.textarea"
                v-model="formField[item.name]"
                :placeholder="'请输入' + item.title"
                :disabled="item.disabled"
                type="textarea"
                :rows="item.rows"
                clearable
              ></ElInput>
              <!-- radio选择器 -->
              <ElRadioGroup
                v-if="item.type == CustomFormColumnsType.radio"
                v-model="formField[item.name]"
                :disabled="item.disabled"
              >
                <ElRadio
                  v-for="(itemRadio, indexRadio) in item.options"
                  :key="indexRadio"
                  :value="itemRadio.value"
                  >{{ itemRadio.text }}</ElRadio
                >
              </ElRadioGroup>
              <!-- select选择器 -->
              <ElSelect
                v-if="item.type == CustomFormColumnsType.select"
                v-model="formField[item.name]"
                :placeholder="'请选择' + item.title"
                :disabled="item.disabled"
              >
                <ElOption
                  v-for="(itemOption, indexOption) in item.options"
                  :key="indexOption"
                  :label="itemOption.text"
                  :value="itemOption.value"
                ></ElOption>
              </ElSelect>
              <!-- 富文本编辑器 -->
              <ArtWangEditor
                v-if="item.type == CustomFormColumnsType.editor"
                v-model="formField[item.name]"
                :height="item.editorOptions?.height"
                :toolbar-keys="item.editorOptions?.toolbarKeys"
                :placeholder="'请输入' + item.title"
                :exclude-keys="item.editorOptions?.excludeKeys"
                :insert-keys="item.editorOptions?.insertKeys"
                :upload-config="item.editorOptions?.uploadConfig"
                :mode="item.editorOptions?.mode"
                @update:model-value="updateEditorValue($event, item.name)"
              ></ArtWangEditor>
            </ElFormItem>
          </ElCol>
        </template>
      </ElRow>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="submit(refElForm)">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>
<script setup lang="ts">
  import { ElMessage, FormInstance } from 'element-plus'
  import { CustomFormColumnsType, CustomFormEmits, CustomInterfaceFormBody } from './it'

  // const props = withDefaults(defineProps<CustomInterfaceFormBody>(), {
  //   visiable: false,
  //   showType: 1,
  //   width: 600
  // })
  const props = withDefaults(
    defineProps<{
      //表单展示状态
      visible: boolean
      //标题
      title?: string
      //展示类型，1.dialog(默认), 2.drawer
      showType?: number
      //弹窗宽度
      width?: number | string
      //表单数据
      formData: CustomInterfaceFormBody
      //表单label的宽度
      labelWidth?: number | string
    }>(),
    {
      visiable: false,
      title: '',
      showType: 1,
      width: 600,
      formData: () => {
        return {}
      },
      labelWidth: 'auto'
    }
  )

  const emit = defineEmits<CustomFormEmits>()
  //表单字段
  const formField = ref<any>({})
  const refElForm = ref()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  //设置弹窗数据
  async function setDialogData() {
    if (props.formData.isEdit && props.formData.getFun) {
      //获取数据
      const primaryKey: string = props.formData.primaryKey || 'id'
      const data: any = await props.formData.getFun({
        [primaryKey]: props.formData.record[primaryKey]
      })
      if (data) {
        props.formData.columns?.forEach((item) => {
          formField.value[item.name] = data[item.name]
        })
      }
    }
  }

  //设置表单内容
  function setFormField() {
    props.formData.columns?.forEach((item) => {
      formField.value[item.name] = item.default || ''
    })
  }

  //添加数据
  function addData() {
    if (props.formData.addFun) {
      props.formData.addFun(formField.value).then((res: any) => {
        if (res) {
          ElMessage.success('添加成功')
          dialogVisible.value = false
          emit('submit', {})
        }
      })
    }
  }

  //编辑数据
  function editData() {
    if (props.formData.editFun) {
      const primaryKey: string = props.formData.primaryKey || 'id'
      const id = props.formData.record[primaryKey]
      props.formData
        .editFun({
          [primaryKey]: id,
          ...formField.value
        })
        .then((res: any) => {
          if (res) {
            ElMessage.success('编辑成功')
            dialogVisible.value = false
            emit('submit', {})
          }
        })
    }
  }

  //提交表单内容
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        if (props.formData.isEdit) {
          //编辑
          editData()
        } else {
          //添加
          addData()
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  //富文本编辑器内容更新
  const updateEditorValue = (value: string, fieldNeme: string) => {
    formField.value[fieldNeme] = value
  }

  watch(
    () => props.visible,
    (newValue) => {
      if (newValue) {
        setFormField()
        //设置弹窗数据
        setTimeout(() => {
          setDialogData()
        }, 50)
      } else {
        refElForm.value.resetFields()
      }
    }
  )
</script>
